/**
 * Utility functions for working with agent template files
 */

import type { DynamicAgentTemplate } from '../types/dynamic-agent-template'

/**
 * Determines if a file is a valid custom agent template file.
 *
 * Custom agent files must:
 * - End with .ts extension
 * - NOT end with .d.ts (TypeScript declaration files)
 *
 * @param fileName - The name of the file to check
 * @returns true if the file is a valid custom agent template
 */
export function isCustomAgentFile(fileName: string): boolean {
  return fileName.endsWith('.ts') && !fileName.endsWith('.d.ts')
}

/**
 * Filters a list of file names to only include valid custom agent template files.
 *
 * @param fileNames - Array of file names to filter
 * @returns Array of file names that are valid custom agent templates
 */
export function filterCustomAgentFiles(fileNames: string[]): string[] {
  return fileNames.filter(isCustomAgentFile)
}

/**
 * Filters an object of file paths/templates to only include valid custom agent templates.
 *
 * @param agentTemplates - Object with file paths as keys
 * @returns Filtered object containing only valid custom agent templates
 */
export function filterCustomAgentTemplates<T>(
  agentTemplates: Record<string, T>,
): Record<string, T> {
  return Object.fromEntries(
    Object.entries(agentTemplates).filter(([filePath]) =>
      isCustomAgentFile(filePath),
    ),
  )
}

/**
 * Extracts the agent ID from a TypeScript file name.
 *
 * @param fileName - The TypeScript file name (e.g., 'my-agent.ts')
 * @returns The agent ID (e.g., 'my-agent')
 */
export function extractAgentIdFromFileName(fileName: string): string {
  return fileName.replace('.ts', '')
}

/**
 * Filters agent templates to include only valid ones, excluding generated files and invalid entries.
 *
 * This method handles various edge cases:
 * - TypeScript declaration files (.d.ts) generated by tools
 * - Frontend key normalization (strips .ts extensions)
 * - Files without extensions
 * - Invalid or empty template data
 *
 * @param agentTemplates - Object with file paths as keys and templates as values
 * @returns Filtered object containing only valid agent templates
 */
export function filterValidAgentTemplates(
  agentTemplates: Record<string, DynamicAgentTemplate>,
): Record<string, DynamicAgentTemplate> {
  return Object.fromEntries(
    Object.entries(agentTemplates).filter(([key, template]) => {
      // Skip if no template data
      if (!template) {
        return false
      }

      // Skip TypeScript declaration files (.d.ts) - these are generated artifacts
      if (key.endsWith('.d.ts')) {
        return false
      }

      // Skip files with invalid extensions (but allow files without extensions)
      // This handles cases where frontend strips .ts but we want to exclude other extensions
      if (key.includes('.') && !key.endsWith('.ts')) {
        // Allow common valid extensions for agent templates
        const validExtensions = ['.ts', '.js', '.mjs']
        const hasValidExtension = validExtensions.some((ext) =>
          key.endsWith(ext),
        )
        if (!hasValidExtension) {
          return false
        }
      }

      // Skip if template doesn't have required fields
      if (!template.id || typeof template.id !== 'string') {
        return false
      }

      // Skip if template has invalid structure
      if (typeof template !== 'object') {
        return false
      }

      return true
    }),
  )
}
